import json
import re

from django.middleware.csrf import get_token
from django.contrib.auth import authenticate, login, logout
from django.http import JsonResponse

from django.views import View
from django_redis import get_redis_connection

from ihome.utils.mixins import LoginRequiredMixin

from ihome.utils import constants

from ihome.utils.qiniuyun.qiniu_storage import storage

from ihome.utils.constants import QINIU_DOMIN_PREFIX
from users.models import User


class CSRFTokenView(View):
    def get(self, request):
        csrf_token = get_token(request)
        print(csrf_token)

        return JsonResponse({'code': 0,
                             'message': 'OK',
                             'csrf_token': csrf_token})


class RegisterView(View):

    def post(self, request):


        req_data = json.loads(request.body.decode())

        mobile = req_data.get('mobile')
        phonecode = req_data.get('phonecode')
        password = req_data.get('password')
        # password2 = req_data.get('password2')

        if not all([mobile, phonecode, password]):
            return JsonResponse({"errno": 400,
                                 "errmsg": "缺少必传参数!"})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': 400,
                                 'errmsg': 'password格式错误'})

        # if password != password2:
        #     return JsonResponse({'errno': 400,
        #                          'errmsg': '两次密码不一致'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 400,
                                 'errmsg': '手机号格式错误'})

        redis_conn = get_redis_connection('verify_code')
        real_sms_code = redis_conn.get('sms_%s' % mobile)

        if real_sms_code is None:
            return JsonResponse({'errno': 400,
                                 'errmsg': '短信验证码已过期!'})

        if phonecode != real_sms_code:
            return JsonResponse({'errno': 400,
                                 'errmsg': '短信验证码错误!'})

        try:
            user = User.objects.create_user(password=password,
                                            username=mobile,
                                            mobile=mobile)
        except Exception as e:
            return JsonResponse({'errno': 400,
                                 'errmsg': '保存用户信息失败!'})

        login(request, user)

        response = JsonResponse({'errno': 0,
                                 'errmsg': '注册成功'})

        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)

        # cart_helper = CartHelper(request, response)
        # cart_helper.merge_cookie_cart_to_redis()

        return response


class LoginView(View):

    def post(self, request):

        req_data = json.loads(request.body.decode())

        mobile = req_data.get('mobile')
        password = req_data.get('password')

        if not all([mobile, password]):
            return JsonResponse({'errno': 400,
                                 'errmsg': '缺少必传参数'})

        User.USERNAME_FIELD = 'mobile'

        user = authenticate(username=mobile, password=password)

        if user is None:
            return JsonResponse({'errno': 400,
                                 'errmsg': '用户名或密码错误'})

        login(request, user)

        return JsonResponse({'errno': 0,
                             'errmsg': 'OK'})

    def get(self, request):

        user = request.user
        if user.is_authenticated:

            return JsonResponse({'errno': 0,
                                 'errmsg': '已登录',
                                 'data': {'name': user.username}})
        else:
            return JsonResponse({'errno': 4101,
                                 'errmsg': '未登录!'})

    def delete(self, request):

        logout(request)

        return JsonResponse({'errno': 0,
                             'errmsg': 'ok'})


class UserInfoView(LoginRequiredMixin, View):

    def get(self, request):

        user = request.user
        # if user.avatar is None:
        #     avatar = 'http://oyucyko3w.bkt.clouddn.com/FmWZRObXNX6TdC8D688AjmDAoVrS'
        # else:
        #     avatar = constants.QINIU_DOMIN_PREFIX + user.avatar
        avatar = QINIU_DOMIN_PREFIX + str(user.avatar)
        info = {"avatar": avatar,
                "create_time": user.date_joined,
                "mobile": user.mobile,
                "name": user.username,
                "user_id": user.id}

        return JsonResponse({"data": info,
                             "errmsg": "OK",
                             "errno": "0"})


# PUT /api/v1.0/user/name
class UserNameChange(View):

    def put(self,requset):

        name = json.loads(requset.body).get('name')
        user = requset.user
        user.username = name

        user.save()

        return JsonResponse({"errno": "0",
                             "errmsg": "修改成功"})


# POST /api/v1.0/user/auth
class UserIdentification(View):

    def post(self,request):
        result = json.loads(request.body)
        real_name = result.get('real_name')
        id_card = result.get('id_card')
        if not all([real_name, id_card]):
            return JsonResponse({
                "errmsg": "400",
                "errno": "缺少必传参数"
            })

        if not re.match(r'^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$',id_card):
            return JsonResponse({
                "errmsg": "400",
                "errno": "身份证输入有误"
            })
        user = request.user
        user.first_name = real_name[1:]
        user.last_name = real_name[0]
        user.id_card = id_card
        user.real_name = real_name
        user.save()
        return JsonResponse({
            "errno": "0",
            "errmsg": "认证信息保存成功"
        })
    def get(self, request):

        user = request.user

        return JsonResponse({'data': {"real_name": request.user.real_name,
                                      "id_card": request.user.id_card},
                             "errno": 0,
                             "errmsg": "OK"})


    """
    def get(self, request):
    return JsonResponse({'errno': '0',
                         'errmsg': 'OK',
                         'data': {'real_name': request.user.real_name,
                                  'id_card': request.user.id_card}})
    """


class Set_User_Avatar_View(View):

    def post(self, request):

        user = request.user
        image_file = request.FILES.get('avatar', None)

        if image_file is None:
            return JsonResponse({
                "code": 400,
                "errmsg": "图片没有输入，不能上传"
            }, status=400)

        image_data = image_file.read()

        try:
            file_name = storage(image_data)

        except Exception as e:
            return JsonResponse({
                "code":400,
                "errmsg": "图片上传失败"
            })

        try:
            User.objects.filter(pk=user.id).update(avatar=file_name)

        except Exception as e:
            print(e)
            return JsonResponse({
                "code": 400,
                "errmsg": "图片保存失败"
            })
        avatar_url = constants.QINIU_DOMIN_PREFIX + file_name

        return JsonResponse({
            "errno": 0,
            "errmsg": "上传头像成功",
             "data": {"avatar_url": avatar_url},
        })



